<template>
	<span :endTime="endTime" :endText="endText" :style="{color: textColor}">
		<slot>{{content}}</slot>
	</span>
</template>

<script>
export default {
  data(){
    return {
      content: '',
      timer:null,
      textColor:"#02a7f0"
    }
  },
  props:{
    endTime:{type:String,default:''},
    startText:{type:String,default:''},
    endText:{type:String,default:'已超时'},
  },
  watch: {
    endTime() {
      this.clearTimer();
      this.countdowm(this.endTime)
    }
  },
  mounted () {
    this.countdowm(this.endTime)
  },
  destroyed() {
    console.log("--------------")
    this.clearTimer();
  },
  methods: {
    clearTimer(){
      if(this.timer){
        clearInterval(this.timer);
      }
    },
    countdowm(timestamp){
      let self = this;
      this.timer = setInterval(function(){
        let nowTime = new Date();
        // console.log(timestamp)
        let endTime = new Date(timestamp) ;
        let t = endTime.getTime() - nowTime.getTime();
        if(t>0){
          let day = Math.floor(t/86400000);
          let hour=Math.floor((t/3600000)%24);
          let min=Math.floor((t/60000)%60);
          let sec=Math.floor((t/1000)%60);
          hour = hour < 10 ? "0" + hour : hour;
          min = min < 10 ? "0" + min : min;
          sec = sec < 10 ? "0" + sec : sec;
          let format = '';
          if(day > 0){
            format = `${day}天${hour}小时`;
          }
          if(day <= 0 && hour > 0 ){
            self.textColor="#d9001b"
            format = `${hour}小时${min}分${sec}秒`;
          }
          if(day <= 0 && hour <= 0){
            self.textColor="#d9001b"
            format =`${min}分${sec}秒`;
          }
          self.content = self.startText+":"+format;
        }else{
          clearInterval(this.timer);
          self.textColor="#d9001b"
          self.content = self.endText;
        }
      },1000);
    }
  }
}
</script>
